class ApplicationController < ActionController::Base
  protect_from_forgery
  rescue_from(Exception, :with => :notify_error)
  before_filter(:set_default_title)
  before_filter(:get_crawler)
  before_filter(:login_required)
  before_filter(:set_timezone)
  
  protected
    def login_required
      redirect_to(welcome_users_path) unless session[:user] || params[:iamarobot] || controller_name == "users"
    end
    
    def notify_error(exception)
      send_error_alert(exception) rescue logger.error($!)
      # still show error page
      raise exception
    end
    
    def set_timezone
      # set the timezone, if there is one in the configatron
      Time.zone = configatron.timezone.to_s if configatron.timezone
    end
    
    def send_error_alert(exception)
      AdminMailer.error(exception, session.to_hash, params, request.env).deliver if Rails.env == "production"
    end

    def set_default_title
      action = {"index" => "", "update" => "Edit ", "create" => "Create ", "new" => "Create ", "edit" => "Edit "}[action_name] || "?"
      obj = controller_name.capitalize
      obj = obj.singularize unless action_name == "index"
      @title = action + obj
    end
    
    def get_crawler
      @crawler = Crawler::Crawler.running
    end
    
    def ajax_request?
      request.env['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' || params[:ajax]
    end
end
